<!--
    * Time    : 2021-01-07 16:00:48
    * Author  : zhangTj
    * Desc    : 账号与安全
-->

<template>
    <div class="w750 mb-3" style="max-width: 750px; margin: 0 auto; width: 100%; height: 100%">
        <van-notice-bar v-if="need" left-icon="volume-o" scrollable text="请完善个人信息" />
        <div class="account">
            <div class="item">
                <div class="entry-con">
                    <div class="con-box">
                        <div style="flex: 0 0 1.5rem">
                            <span class="entry-name ml-7p">姓名</span>
                        </div>
                        <div class="fr flex-1 text-right">
                            <input v-model="userInfo.realName" class="text-right font-12" type="text" placeholder="请设置姓名" />
                        </div>
                    </div>
                </div>
                <div class="entry-con" @click="sexshow = true">
                    <div class="con-box">
                        <div style="flex: 0 0 1.5rem">
                            <span class="entry-name ml-7p">性别</span>
                        </div>
                        <div class="fr flex-1 text-right">
                            <span class="entry-txt" v-if="userInfo.gender == 1">男</span>
                            <span class="entry-txt" v-else-if="userInfo.gender == 2">女</span>
                            <span class="entry-txt" v-else>请设置性别</span>
                        </div>
                    </div>
                </div>
                <div class="entry-con" @click="birthshow = true">
                    <div class="con-box">
                        <div style="flex: 0 0 1.5rem">
                            <span class="entry-name ml-7p">生日</span>
                        </div>
                        <div class="fr flex-1 text-right">
                            <span class="entry-txt" v-if="userInfo.birthDate">{{ userInfo.birthDate | dateformat('YYYY-MM-DD') }}</span>
                            <span class="entry-txt" v-else>请设置生日</span>
                        </div>
                    </div>
                </div>

                <!-- 后台配置的用户信息 -->
                <template v-if="materialFieldList && materialFieldList.length">
                    <div @click="showFieldPopup(field)" v-for="field in materialFieldList" :key="field.id" class="entry-con">
                        <div class="con-box">
                            <div style="flex: 0 0 1.5rem">
                                <span style="color: #ee4133" v-if="field.required">*</span>
                                <span class="entry-name" :class="field.required ? '' : 'ml-7p'">{{ field.fieldName }}</span>
                            </div>
                            <div class="fr flex-1 text-right line-clamp1 flex-1">
                                <template v-if="field.fieldType == 'TEXT'">
                                    <input
                                        v-if="field.edit || !copyExtInfos[field.fieldKey]"
                                        v-model="extInfos[field.fieldKey]"
                                        :placeholder="field.placeholder"
                                        class="font-12 text-right"
                                    />
                                    <span v-else class="font-12 text-right">{{ extInfos[field.fieldKey] }}</span>
                                </template>
                                <template v-if="field.fieldType == 'NUMBER'">
                                    <input
                                        v-if="field.edit || !copyExtInfos[field.fieldKey]"
                                        v-model="extInfos[field.fieldKey]"
                                        type="number"
                                        :placeholder="field.placeholder"
                                        class="font-12 text-right"
                                    />
                                    <span v-else class="font-12 text-right">{{ extInfos[field.fieldKey] }}</span>
                                </template>
                                <template v-if="field.fieldType == 'SELECT'">
                                    <span class="entry-txt">{{ extInfos[field.fieldKey] || field.placeholder }}</span>
                                </template>
                                <template v-if="field.fieldType == 'DATE'">
                                    <span class="entry-txt">{{ extInfos[field.fieldKey] || field.placeholder }}</span>
                                </template>
                                <template v-if="field.fieldType == 'ADDRESS'">
                                    <span class="entry-txt">{{ extInfos[field.fieldKey].addNameStr || field.placeholder }}</span>
                                </template>
                                <template v-if="field.fieldType == 'CHECKBOX'">
                                    <span class="entry-txt">
                                        {{ extInfos[field.fieldKey].length ? extInfos[field.fieldKey].join(',') : field.placeholder }}
                                    </span>
                                </template>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- 保存用户信息 -->
        <div @click="saveUserInfo" class=" position-fixed bottom-0 w-100 text-center bg-main text-fff py-1" style="max-width: 750px;">
            <span>保存</span>
        </div>

        <!-- 性别弹窗 -->
        <van-popup v-model="sexshow" position="bottom">
            <van-picker show-toolbar :columns="columns" @cancel="onCancel" @confirm="sexConfirm" />
        </van-popup>

        <!-- 自定义字段select弹窗 -->
        <van-popup v-model="showPickup" position="bottom">
            <van-picker show-toolbar :columns="fieldColumns" @cancel="onCancel" @confirm="confirmField" />
        </van-popup>

        <!-- 自定义字段Date弹窗 -->
        <van-popup v-model="showDateup" position="bottom">
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                :min-date="minDate"
                :max-date="maxDate"
                :formatter="formatter"
                @cancel="onCancel"
                @confirm="fieldDateConfirm"
            />
        </van-popup>

        <!-- 生日弹窗 -->
        <van-popup v-model="birthshow" position="bottom">
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                :min-date="minDate"
                :max-date="maxDate"
                :formatter="formatter"
                @cancel="onCancel"
                @confirm="dateConfirm"
            />
        </van-popup>

        <!-- 地区选择 -->
        <address-select v-model="addressShow" title="地址" mode="id" @confirm="confirmAddress" :defaultValue="defaultValue" />

        <!-- 多选框弹窗 -->
        <van-action-sheet v-model="checkBoxShow" :title="checkBoxTitle" :closeable="false">
            <div>
                <van-checkbox-group class="ellipsis" v-model="checkBoxResult">
                    <van-cell-group>
                        <van-cell v-for="(item, index) in checkBoxList" clickable :key="index" :title="`${item}`" @click="toggle(index)">
                            <template #right-icon>
                                <van-checkbox :name="item" ref="checkboxes" />
                            </template>
                        </van-cell>
                    </van-cell-group>
                </van-checkbox-group>
                <div class="grid-column2 text-center py-1 font-14">
                    <div @click="checkBoxShow = false" class="text-999">
                        <span>取消</span>
                    </div>
                    <div @click="confirmCheckBox">
                        <span>确定</span>
                    </div>
                </div>
            </div>
        </van-action-sheet>
    </div>
</template>

<script>
import { getUserInfo, materialFieldSetting, userInfoSave } from 'api/account'
import addressSelect from '@/components/addressSelect/addressSelect'

export default {
    name: '',
    components: { addressSelect },
    data() {
        return {
            need: '', // finish => 表示是从登录页面跳转过来的，需要展示走马灯和保存时跳转到首页
            birthshow: false,
            sexshow: false,
            minDate: new Date(1930, 0, 1), // 时间组件的最小时间
            maxDate: new Date(), // 时间组件的最大时间
            columns: ['男', '女'],
            currentDate: new Date(), // 当前年月日

            userInfo: {}, // 用户信息
            materialFieldList: [], // 后台配置用户信息字段
            extInfos: {}, // 扩展字段
            showPickup: false, // 展示自定义selct弹窗
            fieldColumns: [], // 扩展字段的select
            showDateup: false, //  展示自定义date弹窗
            activeField: {}, // 激活弹窗的自定义字段
            addressShow: false, // 地区组件弹窗
            defaultValue: [], // 地区选择的默认会先值
            checkBoxShow: false, // 多选框
            checkBoxTitle: '标题', // 多选框标题
            checkBoxList: [], // 多选框选择数据
            checkBoxResult: [], // 多选框选中项
            copyExtInfos: {} //复制一份extInfos原始数据
        }
    },
    computed: {},
    watch: {},
    created() {},
    destroyed() {},
    mounted() {
        if (this.$route.query.need) {
            this.need = this.$route.query.need
        }
        if (this.$route.query.redirect) {
            this.redirect = this.$route.query.redirect
        }
        this.getInfo()
    },
    methods: {
        // 获取用户信息
        getInfo() {
            getUserInfo()
                .then((res) => {
                    if (!res.success) {
                        this.$toast({ duration: 1000, message: res.msg })
                    }
                    this.userInfo = res.result
                    this.$nextTick(() => {
                        this.userInfoSetting()
                    })
                })
                .catch((err) => {
                    this.$toast({ duration: 1000, message: '获取数据失败' })
                })
        },

        // 获取后台配置的个人信息字段
        userInfoSetting() {
            materialFieldSetting()
                .then((res) => {
                    if (!res.success) {
                        this.$toast(res.msg)
                        return
                    }
                    this.materialFieldList = res.result
                    for (let field of res.result) {
                        this.extInfos[field.fieldKey] =
                            this.userInfo.extInfos && this.userInfo.extInfos[field.fieldKey]
                                ? this.userInfo.extInfos[field.fieldKey]
                                : field.defaultValue || ''
                    }
                    // 保存一份原始数据
                    this.copyExtInfos = JSON.parse(JSON.stringify(this.extInfos))
                })
                .catch((err) => {
                    this.$toast(err.msg)
                })
        },

        //生日确认弹窗
        dateConfirm(value) {
            this.$set(this.userInfo, 'birthDate', this.$dateformat(value, 'YYYY-MM-DD'))
            this.birthshow = false
        },

        // Date自定义时间弹窗
        fieldDateConfirm(value) {
            this.$set(this.extInfos, this.activeField.fieldKey, this.$dateformat(value, 'YYYY-MM-DD'))
            this.onCancel()
        },

        //性别确认弹窗
        sexConfirm(value) {
            this.$set(this.userInfo, 'gender', value == '男' ? 1 : 2)
            this.sexshow = false
        },

        // 确定自定义弹窗
        confirmField(value) {
            this.$set(this.extInfos, this.activeField.fieldKey, value)
            this.onCancel()
        },

        // 保存用户信息
        saveUserInfo() {
			// 自定义字段判断是否必填
			for (let field of this.materialFieldList) {
			    if (field.required && !this.extInfos[field.fieldKey]) {
			        this.$toast(field.placeholder)
			        return
			    }
			}
			this.$utils.uDebounce(() => {
				userInfoSave({
				    birthDate: this.userInfo.birthDate,
				    gender: this.userInfo.gender,
				    realName: this.userInfo.realName,
				    extInfos: this.extInfos
				})
				    .then((res) => {
				        if (!res.success) {
				            this.$toast(res.msg)
				            return
				        }
						this.handleSaveInfo()
				    })
				    .catch((err) => {
				    })
			})
            
        },
        // 除了input，显示弹窗
        showFieldPopup(field) {

            if (this.extInfos[field.fieldKey] && this.copyExtInfos[field.fieldKey]) {
                if (!field.edit) {
                    this.$toast(`${field.fieldName}不可修改`)
                    return
                }
            }
            if (field.fieldType == 'TXT' || field.fieldType == 'NUMBER') {
                return
            }
            if (field.fieldType == 'SELECT') {
                this.fieldColumns = field.optionList.map((item) => item.value)
                this.showPickup = true
            }
            if (field.fieldType == 'DATE') {
                this.showDateup = true
                this.currentDate = this.extInfos[field.fieldKey] ? new Date(this.extInfos[field.fieldKey]) : new Date()
            }
            if (field.fieldType == 'ADDRESS') {
                this.addressShow = true
                // 如果有默认值则设置
                if (!this.$utils.test.isEmpty(this.extInfos[field.fieldKey])) {
                    const addNameStr = this.extInfos[field.fieldKey].addNameStr.split(' ')
                    const addIdList = this.extInfos[field.fieldKey].addIdList
                    this.defaultValue = [
                        { name: addNameStr[0], key: addIdList[0] },
                        { name: addNameStr[1], key: addIdList[1] },
                        { name: addNameStr[2], key: addIdList[2] },
                        { name: addNameStr[3], key: addIdList[3] }
                    ]
                }
            }
            if (field.fieldType == 'CHECKBOX') {
                this.checkBoxShow = true
                this.checkBoxTitle = `${field.fieldName}`
                this.checkBoxList = field.checkboxOptionsList
                this.checkBoxResult = this.extInfos[field.fieldKey] ? this.extInfos[field.fieldKey] : []
            }
            this.activeField = field
        },

        //关闭弹窗
        onCancel() {
            this.birthshow = false
            this.sexshow = false
            this.showPickup = false
            this.showDateup = false
            this.addressShow = false
            this.checkBoxShow = false
        },

        // 时间组件格式化函数
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            } else if (type === 'month') {
                return `${value}月`
            } else if (type === 'day') {
                return `${value}日`
            }
            return value
        },

        // 地址
        confirmAddress(event) {
            this.$set(this.extInfos, this.activeField.fieldKey, { addIdList: event.keyId, addNameStr: event.addressStr })
        },

        // 确定多选框
        confirmCheckBox() {
            this.$set(this.extInfos, this.activeField.fieldKey, this.checkBoxResult)
            this.onCancel()
        },

        toggle(index) {
            this.$refs.checkboxes[index].toggle()
        },
		handleSaveInfo() {
			this.$store.dispatch('setupInfo');
			this.$toast({
			    message: '编辑成功',
			    onClose: () => {
			        // 如果存在重定向，则优先使用重定向
			        if (this.redirect) {
			            this.$router.replace({ path: this.$route.query.redirect })
			            return
			        }
							
			        // 判断是否是从首页过来的，如果是则返回到首页
			        if (this.need) {
			            this.$router.replace('/index')
			        } else {
			            // this.getInfo()
						this.$router.back()
			        }
			    }
			})
		}
    }
}
</script>

<style scoped>
	.ellipsis { 
		text-overflow: ellipsis;
		overflow: hidden;
		display: -webkit-inline-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;word-wrap: break-word;word-break: break-all;
	}
</style>
<style src="../../assets/css/account.css" scoped></style>
